package uk.ac.ebi.dod.utils;

import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.LogManager;

import org.apache.commons.logging.LogFactory;
/**
 * Writes JDK log messages to commons logging.
 *
 * @author Florian Reisinger
 * @since 0.1
 */
public class LogRedirector {
    static JDKLogHandler activeHandler;

    /**
     * Activates the redirector.
     */
    public static void activate() {
        try {
            Logger rootLogger = LogManager.getLogManager().getLogger("");
            // remove old handlers
            for (Handler handler : rootLogger.getHandlers()) {
                rootLogger.removeHandler(handler);
            }
            // add our own
            activeHandler = new JDKLogHandler();
            activeHandler.setLevel(Level.ALL);
            rootLogger.addHandler(activeHandler);
            rootLogger.setLevel(Level.ALL);
            // done, let's check it right away!!!

            Logger.getLogger(LogRedirector.class.getName()).info("activated: sending JDK log messages to Commons Logging");
        } catch (Exception exc) {
            LogFactory.getLog(LogRedirector.class).error("activation failed", exc);
        }
    }

    /**
     * Deactivate the redirector.
     */
    public static void deactivate() {
        Logger rootLogger = LogManager.getLogManager().getLogger("");
        rootLogger.removeHandler(activeHandler);

        Logger.getLogger(LogRedirector.class.getName()).info("dactivated");
    }

}

